import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { StateType } from '../../store/reducer'
const App = () => {
	const car = useSelector((state: StateType) => state.car)
	const [totalPrice, setTotalPrice] = useState(0)
	const [totalCheck, setTotalCheck] = useState(false)
	const dispatch = useDispatch()

	useEffect(() => {
		let price = 0
		car.forEach((v) => {
			price += v.isChecked ? v.count * v.price : 0
		})
		setTotalPrice(price)

		const check = car.every(v => v.isChecked)
		console.log(check);
		
		setTotalCheck(check)

	}, [car])

	return (
		<>
			购物车
			<div className="list-car">
				{
					car.length > 0 && car.map((v, i) => {
						return (
							<div className='list-car-item' key={i}>
								<input type="checkbox" checked={ v.isChecked }  onChange={ () => dispatch({ type: 'switchCheck', payload: v }) }/>
								<dl >
									<dt>
										<img src={v.url} alt="" />
									</dt>
									<dd>
										<h3>{v.title}</h3>
										<p>{v.desc}</p>
										<p>{v.price}</p>
										<p>
											<button style={{ padding: '6px' }} onClick={() => dispatch({ type: 'subCar', payload: v })}>-</button>
											<span>{v.count}</span>
											<button style={{ padding: '6px' }} onClick={() => dispatch({ type: 'addCar', payload: v })}>+</button>
										</p>
									</dd>
								</dl>
							</div>
						)
					})
				}
			</div>


			<div>
				<h1>
					全选<input type="checkbox" checked={ totalCheck } onChange={ (e) => dispatch({ type: 'switchCheckAll', payload: e.target.checked }) }/>
					总价: {totalPrice}
				</h1>
			</div>
		</>
	)
}


export default App